package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.R;
import com.itheima.entity.User;
import com.itheima.exception.CustomException;
import com.itheima.service.UserService;
import com.itheima.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author Tang
 * @date 2023/4/15
 */
@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 发送短信验证码
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        String phone = user.getPhone();
        if (phone == null) {
            throw new CustomException("请输入手机号！");
        }

        //1.调用工具类提供给的方法，生成验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        log.info("code:{}",code);

        //2.缓存验证码，使用session，将验证码存到session中
       // session.setAttribute(phone, code.toString());

        //缓存验证码将验证码存到redis中
        redisTemplate.opsForValue().set(phone,code);

        //3.调用短信发送工具类，发送短信给用户
        //SMSUtils.sendMessage("瑞吉外卖登录","SMS_276440575",phone,code.toString());

        //4.返回结果，发送成功
        return R.success("短信发送成功！");
    }

    /**
     * 手机验证码登录
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<String> login(@RequestBody Map<String,String> map, HttpSession session){
        //1.获取前端传递过来的手机号和验证码
        String phone = map.get("phone");
        String code = map.get("code");
        if (phone == null || code == null) {
            throw new CustomException("请输入手机号或验证码！");
        }

        //2.根据手机号查询数据库user表，如果存在该用户，直接验证验证码
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, phone);
        User one = userService.getOne(wrapper); //one = null;
        if (one == null) {
            //3.如果不存在该用户，需要初始化用户数据
            one = new User();
            one.setPhone(phone);
            one.setName("u_"+phone);
        }
        //4.将session中缓存的验证码和前端传递过来的验证码对比，如果不一致，直接返回错误信息
        //   String validteCode = (String) session.getAttribute(phone);
        //优化 从 redis中将验证码取出
       String validteCode =(String) redisTemplate.opsForValue().get(phone);

        if (!code.equals(validteCode)) {
            throw new CustomException("验证码不匹配");
        }

        //5.登录验证成功，将用户初始化到数据库,不存在该用户的时候insert操作，如果存在update操作
        userService.saveOrUpdate(one);

        //6.返回登录成功结果，清理验证码，缓存用户id（为了登录校验做准备）
        redisTemplate.delete(phone);
        session.setAttribute("user", one.getId());
        return R.success("登录成功！");
    }
    @PostMapping("/loginout")
    public R<String> loginOut(HttpSession httpSession){
        httpSession.removeAttribute("user");
        return R.success("退出登錄");
    }
}
